<?php

/**
 * JingYao-backend
 *
 * @link     https://gitee.com/wang-zhihui-release/jingyao-backend
 * @apiDocument https://gitee.com/wang-zhihui-release/jingyao-backend/wikis/
 */

namespace App\Services;

use App\Exceptions\ApiException;
use Illuminate\Http\UploadedFile;
use Overtrue\CosClient\ObjectClient;

class CosService
{
    protected $objectClient;

    /**
     * @var \Illuminate\Config\Repository|\Illuminate\Contracts\Foundation\Application|mixed
     */
    private $config;

    public function __construct()
    {
        $this->config = config('cos');
        $this->objectClient = new ObjectClient($this->config);
    }

    /**
     * @param string $dir 要上传去的目录 如 test/2021-01-01/
     *                    其实 COS 并没有目录的概念 只是便于人类操作
     * @throws ApiException
     */
    public function uploadFile(string $dir, UploadedFile $file): string
    {
        if (env('APP_ENV') != 'pro') {
            $dir = 'test/' . $dir;
        }
        $key = $dir . $this->genFileName($file);
        try {
            $this->objectClient->putObject($key, $file->getContent());
        } catch (\Exception $exception) {
            throw new ApiException($exception->getMessage(), 1);
        }

        return $this->config['upload_domain'] . $key;
    }

    public function uploadFileNormal(string $filePath, string $fileContent): string
    {
        $res = $this->objectClient->putObject($filePath, $fileContent);
        if ($res->getStatusCode() == 200) {
            return $this->config['upload_domain'] . $filePath;
        }
        throw new \Exception('上传异常');
    }

    private function genFileName(UploadedFile $file): string
    {
        $clientOriginalName = $file->getClientOriginalName();
        $fileNameArr = explode('.', $clientOriginalName);
        $ex = end($fileNameArr);
        $rand = time() + rand(0000, 9999);
        $uniqName = strtoupper(md5((string)$rand));
        $originName = $file->getClientOriginalName();
        return sprintf('%s_%s.%s', $uniqName, $originName, $ex);
    }
}
